import CryptoJS from 'crypto-js'
import router from "@/router/index";

const production = false//process.env.NODE_ENV === 'production' ? true:false
function encrypt(key, data) {
    try {
        if(!production) return JSON.stringify(data)
        const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), key).toString()
        return ciphertext
    } catch(err) {
        localStorage.clear()
        sessionStorage.clear()
        router.push('/login')
    }
}
function decrypt(key, ciphertext) {
    try {
        if(!production) return JSON.parse(ciphertext)
        const bytes  = CryptoJS.AES.decrypt(ciphertext, key);
        const decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
        return decryptedData
    } catch(err) {
        localStorage.clear()
        sessionStorage.clear()
        router.push('/login')
    }
}
/**
 * 浏览器本地仓库storage管理
 */
export default {
    setLocalStorage(key,value){
        const ciphertext = encrypt(key, value)
        localStorage.setItem( key, ciphertext )
    },
    getLocalStorage(key){
        const value = localStorage.getItem(key)
        const decryptedData = value ? decrypt(key, value ): null
        return decryptedData
    },
    removeLocalStorage(key){
        localStorage.removeItem(key)
    },
    clearLocalSrtorage(){
        localStorage.clear()
    },
    setSessionStorage(key,value){
        const ciphertext = encrypt(key, value)
        sessionStorage.setItem( key, ciphertext )
    },
    getSessionStorage(key){
        const value = sessionStorage.getItem(key)
        const decryptedData = value ? decrypt(key, value ): null
        return decryptedData
    },
    removeSessionStorage(key){
        sessionStorage.removeItem(key)
    },
    clearSessionStorage(){
        sessionStorage.clear()
    }
}
